<template>
  <basic-container>
    <el-container> 
      <el-aside width="230px">
        <div  v-if="showLoading"  style="width:100%; color:#69b3fc;font-size:25px;top:60px;left:90px; position:absolute;z-index:5000">
          <i  class="el-icon-loading"></i><span style="font-size:12px;">目录加载中...</span>
        </div>
        <avue-tree :option="treeOption" :data="treeData"  @update="updataCatalog" @save="saveNewCatalog" @del="deleteCatalog" v-model="catalogForm" @node-click="treeNodeClick">
          <span class="el-tree-node__label" slot-scope="{node,data}">
            <span>
              <svg-icon iconClass="folder"/>
              <span style="color:#333333; ">{{data.catalogName}}</span>
              <span style="color:#666666">
                {{data.readFlag?'[共享]':''}}
              </span>
            </span>
          </span>
        </avue-tree>
      </el-aside>
      <el-main class='fileElmain'>
        <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :defaults.sync="showColumn"
                  :permission="permissionList"
                  :page.sync="page"
                  :before-open="beforeOpen"
                  @sortable-change="sortableChange" 
                  @refresh-change="refreshChange"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @filter="filterChange"
                  @sort-change="sortChange" 
                  @on-load="onLoad">
          <template slot-scope="scope" slot="menu">
          </template>
          <template slot-scope="scope" slot="menuLeft">
            <el-button v-if="mode == 'select'" type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click.stop="handleBatchAddFile">添加
            </el-button>
             <el-button v-if="mode == 'select'" type="primary"
                      size="small"
                      @click.stop="openBatchAddDialog">上传
                      <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <el-button v-if="mode == 'save'" type="primary"
                      size="small"
                      icon="el-icon-check"
                      @click.stop="saveFile">保存
            </el-button>
           
          </template>
          <template slot="fileName" slot-scope="scope">
              <svg-icon v-if="scope.row.fileType == 'xlsx' || scope.row.fileType == 'xls'" iconClass="excel"/>
              <svg-icon v-else-if="scope.row.fileType == 'pptx' || scope.row.fileType == 'ppt'" iconClass="ppt"/>
              <svg-icon v-else-if="scope.row.fileType == 'pdf'" iconClass="pdf"/>
              <svg-icon v-else-if="scope.row.fileType == 'docx' || scope.row.fileType == 'doc'" iconClass="word"/>
              <svg-icon v-else-if="scope.row.fileType == 'txt'" iconClass="txt"/>
              <el-image v-else-if="scope.row.fileType == 'png' || scope.row.fileType == 'bmp' || scope.row.fileType == 'gif' || scope.row.fileType == 'jpg' || scope.row.fileType == 'jpeg'"
                style="border-radius:5px; padding:5px 5px 0 0;width: 30px; height: 30px"
                :src="'/'+scope.row.filePath" 
                :preview-src-list="['/'+scope.row.filePath]">
              </el-image>
              <svg-icon v-else iconClass="unknown"/>
              <span @click.stop="openOfficeDialog(scope.row)" style="color:#46a0fc;font-weight:bold;cursor:pointer">{{scope.row.fileName}}</span>
              <!-- <i :class="scope.row.icon" style="font-size:24px"></i> -->
          </template>
        </avue-crud>
      </el-main>
    </el-container> 
    <!-- 
      上传文件对话框
     -->
    <el-dialog title="上传文件" :modal='false' width='50%' :close-on-click-modal='false' :visible.sync="batchAddDialog">
      <el-upload
        class="upload-demo"
        action="/file/upload"
        :headers="headersParam"
        :data="dataParam"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="10"
        drag
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :file-list="fileList">
       <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handlelSaveFile($event)" data-clipboard-target="#pathText">保存</el-button>
        <el-button size="small" @click="batchAddDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>

import {queryFileCatalogTree,saveGeneralFileCatalog,updateGeneralFileCatalog,deleteGeneralFileCatalog} from '@/api/general/file/generalFileCatalogApi';
import {exportGeneralFileInfoExcel,saveOrUpdateGeneralFileInfo,saveOrUpdateGeneralFileInfoList,saveGeneralFileInfo,saveGeneralFileInfoList,deleteGeneralFileInfo,queryGeneralFileInfo,queryGeneralFileInfoListPage,updateGeneralFileInfo,deleteGeneralFileInfoList} from '@/api/general/file/generalFileInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat, copyToClipboard} from '@/util/util';
import {getToken} from '@/util/auth'
import {Base64} from 'js-base64';
import NProgress from 'nprogress'

export default {
  props: {
    mode:{
      type: String
    },
    fileInfo: {
      type: Object
    }
  },
  data() {
    return {
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      selectionList: [],
      loading: false, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 12,
        tip: false,
        border: false,
        selection: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: true,
        printBtn:false,
        editBtn: false,
        saveBtn: false,
        filterBtn:false, 
        columnBtn: false,    
        menu: false,     
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '文档ID',
            prop: 'id', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '文档名称',
            prop: 'fileName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: true,
            hide: false,
            overHidden: true,
            slot: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '文档大小',
            prop: 'fileSize', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            disabled:true,
            width: 80,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ]
      },
      data: [],

      //上传文件
      headersParam:{},
      dataParam:{},
      fileList: [],

      // 组织目录树形区
      showLoading: true,
      hasFoundParent: false,
      checkedNode: '',
      catalogForm:{},
      currentCatalog: {},
      treeData:[],
      lastParentId: '',
      lastParentCatalogName: '',
      treeOption:{
        title:'新增根目录',
        addBtn: true,
        menu: true,
        defaultExpandAll:false,
        props: {
          labelText: '目录名称',
          label: 'catalogName',
          value: 'id',
          children:'children'
        },
      },
     
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_file_add, false),
        viewBtn: this.vaildData(this.permission.general_file_view, false),
        delBtn: this.vaildData(this.permission.general_file_delete, false),
        editBtn: this.vaildData(this.permission.general_file_edit, false),
        printBtn: this.vaildData(this.permission.general_file_print, false),
        searchBtn:this.vaildData(this.permission.general_file_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 添加新的目录
     */
    async saveNewCatalog(parent,data,done,loading){
      let cid = new Date().getTime();
      this.catalogForm.id = cid;
      this.catalogForm.children=[];
      //this.$console.log('====parent data == ', parent);
      let paretId = this.userInfo.userId;
      if(parent.id){
        paretId = parent.id;
      }
      //写记录
      this.reqParams.singleBody = {
        catalogName: data.catalogName,
        parentCatalogId: paretId,
        parentCatalogName: this.lastParentCatalogName,
        ownerId: this.userInfo.userId,
        orderSeq: 0
      };
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralFileCatalog(this.commonData).then(() => {
        this.singleBody={};
        this.getCatalogTree();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        done(); 
      }, error => {
        //this.$console.log(error);
        loading();
      });         
    },
    
    /**
     * 修改目录名称
     */
    updataCatalog(data, parent, done,loading){
      if((data.readFlag == '1' || data.readFlag == '2') && data.ownerId != this.userInfo.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '共享文档不能修改名字!'
        });
        return false;
      }
      this.reqParams.singleBody = this.catalogForm;
      this.reqParams.singleBody.tenantId = localStorage.getItem('tenantId') || 'DOOL1001';
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralFileCatalog(this.commonData).then(() => {
        this.singleBody={}
        this.getCatalogTree();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '修改成功!'
        });
        done();
      }, error => {
        //this.$console.log(error);
        loading();
      });
    },
    /**
     * 删除目录名
     */
    deleteCatalog(data,done,loading){
      if((data.readFlag == '1' || data.readFlag == '2') && data.ownerId != this.userInfo.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '共享文档不能删除!'
        });
        return false;
      }
      this.$confirm('删除后当前目录下的文件将一并删除，确定将选择的目录删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          done();
          this.reqParams.singleBody = data;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFileCatalog(this.commonData);
        })
        .then(() => {
          this.getCatalogTree();
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    
    /**
     * 批量新增记录,调用父组件方法
     */
    handleBatchAddFile(){
      if(this.selectionList.length == 0){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '未选择任何文件!'
        });
        return false;
      }
      this.$emit('handleAddFile', this.selectionList);
      this.currentCatalog = {};
    },
    /**
     * 目录树形菜单点击时触发事件
     */
    treeNodeClick(data){
      this.currentCatalog = data
      this.singleBody={
        catalogId: data.id
      }
      this.onLoad(this.page);
      if(data.readFlag == '1'){
        this.permission.general_file_edit = false;
        this.permission.general_file_delete = false;
        this.permission.general_file_batch_delete = false;
      }
      else{
        this.permission.general_file_edit = true;
        this.permission.general_file_delete = true;
        this.permission.general_file_batch_delete = true;
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      if(!this.currentCatalog.id){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请选择一个左边的目录再上传！'
        });
        return false;
      }
      this.batchAddDialog = true;
    },
    /**
     * 上传成功回调
     */
    handleSuccess(response, file, fileList){
      if(response.head.respCode == 'S0000'){
        this.fileList = fileList;
      }
      else{
        file.status = 'error'
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: response.respMsg
        });
      }
    },
    /**
     * 保存记录
     */
    handlelSaveFile() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      loading.close();
      var dataList = [];
      if(this.fileList.length > 0){
        this.fileList.forEach((element,index) => {
          if(element.status  ==  'success'){
            dataList.push({
              fileName: element.response.fileName,
              filePath:element.response.filePath,
              fileSize:element.response.fileSize,
              fileType:element.response.fileType,
              catalogId: this.currentCatalog.id,
              ownerId: this.userInfo.userId
            });
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralFileInfoList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
          this.batchAddDialog = false;
        }, error => {
          //this.$console.log(error);
          loading.close();
          this.batchAddDialog = false;
        });      
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '请选择文件上传后再保存!'
        });
      }
    },
    /**
     * 另存为保存文件
     */
    saveFile(){
      if(!this.currentCatalog.id){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请选择一个左边的目录再保存！'
        });
        return false;
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      
      this.reqParams.singleBody = {
        fileName: this.fileInfo.fileName,
        filePath: this.fileInfo.filePath,
        fileSize: this.fileInfo.fileSize,
        fileType: this.fileInfo.fileType,
        catalogId: this.currentCatalog.id,
        ownerId: this.userInfo.userId
      };
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralFileInfo(this.commonData).then(() => {
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        loading.close();
        this.$emit('closeFileDialog');
      }, error => {
        //this.$console.log(error);
        loading.close();
      }); 
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      if(!this.currentCatalog.id){
        this.singleBody.ownerId = this.userInfo.userId;
      }
      this.orderRules = {
        order: 'descending',
        prop: 'file_name'
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFileInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        queryGeneralFileInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    
    /**
     * 打开在线编辑窗口
     */
    openOfficeDialog(row){
      if(row.fileType == 'ppt' || row.fileType == 'pptx' || row.fileType == 'doc'  || row.fileType == 'docx'  || row.fileType == 'xls' || row.fileType == 'xlsx'  || row.fileType == 'pdf'){
      }
      else if(row.fileType == 'png' || row.fileType == 'jpeg' || row.fileType == 'jpg' || row.fileType == 'gif' || row.fileType == 'bmp') {
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请直接点击小图片放大!'
        });
        return false;
      }
      else {
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '该文件不支持在线阅读!'
        });
        return false;
      }
      let mode = 'edit'
      if(this.currentCatalog.readFlag == '1'){
        mode = 'view'
      }
      let openUrl= 'id='+Base64.encode(row.id)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode='+mode;
      window.open('/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
    },
    
    /**
     * 获取目录树
     */
    getCatalogTree(){
      // 加载树形目录列表
      this.showLoading = true;
      this.singleBody = {
        parentCatalogId: this.userInfo.userId
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 9999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryFileCatalogTree(this.commonData).then(res => {
        this.treeData = res.data.body.listBody;
        this.showLoading = false;
      }, error => {
      });
    },
  },
  created() {
       
  },
  mounted() {
    this.getCatalogTree();
    //初始化文件上传头信息
    this.headersParam={
      'Authorization': 'bearer ' + getToken(),
      'UserId': this.userInfo.userId,
      'UserSign':'uploadFile',
      'remote': 'no'
    }
  },
};
</script>
<style>
.el-main {
    margin-left: 5px !important;  
    border-left: 10px solid #f3f3f3 !important;  
}
.historyCrud .avue-crud__menu{
  display: none !important;
}
.fileElmain .el-collapse-item__content .avue-form__group .el-col-md-6{
  width: 50% !important;
}
.fileElmain  .avue-crud__search .avue-form__menu--center{
  width: 50% !important;
}
.templateClass{
  cursor:pointer;
  border: 1px solid #f3f3f3;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  padding:10px;
  margin: 10px;
  height: 200px;
  width: 150px;
}
.labelClass{
  padding:10px;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  text-align: center;
}
</style>
